const { Sequelize, Op } = require("sequelize");
const dailySentence = require("../sequelize/dailySentence");

class Service {
	async getOne() {
		try {
			return {
				code: 200,
				message: "ok",
				result: await dailySentence.findOne({
					where: {
						[Op.and]: [
							Sequelize.where(
								Sequelize.fn(
									"DATE",
									Sequelize.col("createTime")
								), // 表对应的字段
								Sequelize.literal("CURRENT_DATE")
							),
						],
					},
				}),
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async list(query) {
		try {
			const pageNum = parseInt(query.pageNum) || 1;
			const pageSize = parseInt(query.pageSize) || 10;

			const rows = await dailySentence.findAndCountAll({});
			return {
				code: 200,
				message: "ok",
				result: {
					list: await dailySentence.findAll({
						limit: pageSize,
						offset: (pageNum - 1) * pageSize,
						order: [["createTime", "DESC"]],
					}),
					count: rows.count,
				},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async add(body) {
		try {
			await dailySentence.create({ ...body, createTime: new Date() });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async update(body) {
		try {
			await dailySentence.update(body, { where: { id: body.id } });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async del(id) {
		try {
			await dailySentence.destroy({
				where: {
					id,
				},
			});
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}
}

module.exports = new Service();
